package com.niedziela12.pai.sessionbeans;

import com.niedziela12.pai.ejb.dto.ReservationDTO;
import com.niedziela12.pai.ejb.entities.Reservation;
import com.niedziela12.pai.ejb.reservation.endpoints.ReservationEndpoint;
import com.niedziela12.pai.ejb.reservation.endpoints.ReservationEndpointLocal;
import com.niedziela12.pai.ejb.reservation.facades.ReservationFacadeLocal;
import com.niedziela12.pai.ejb.user.endpoints.UserEndpointLocal;
import com.niedziela12.pai.sessionbeans.util.JsfUtil;
import com.niedziela12.pai.sessionbeans.util.PaginationHelper;

import java.io.Serializable;
import java.util.Calendar;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;

@ManagedBean(name = "reservationController")
@SessionScoped
public class ReservationController implements Serializable {

    private ReservationDTO current;
    private DataModel items = null;
    @EJB
    private ReservationEndpointLocal reservationEndpoint;
    @EJB
    private UserEndpointLocal userEndpoint;
    private PaginationHelper pagination;
    private int selectedItemIndex;

    @ManagedProperty(value = "#{userRights}")
    private UserRights userRights;

    public void setUserRights(UserRights userRights) {
        this.userRights = userRights;
    }
    
    public ReservationController() {
    }

    public ReservationDTO getSelected() {
        if (current == null) {
            current = new ReservationDTO();
            selectedItemIndex = -1;
        }
        return current;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {
                private int reservationCount = -1;
                @Override
                public int getItemsCount() {
                    if(reservationCount > -1)
                        return reservationCount;
                    return reservationEndpoint.getReservationsCount();
                }

                @Override
                public DataModel createPageDataModel() {
                    if(userRights.isModerator()){ // dla admina wszystkie rekordy
                        reservationCount = -1;
                        return new ListDataModel(reservationEndpoint.getReservations(getPageFirstItem(), getPageFirstItem() + getPageSize()));
                    }
                    else{
                        ListDataModel list = new ListDataModel(reservationEndpoint.getReservationForUser(FacesContext.getCurrentInstance().getExternalContext().getRemoteUser()));
                        reservationCount = list.getRowCount();
                        return list;
                    }
                }
            };
        }
        return pagination;
    }
    
    public String prepareList() {
        recreateModel();
        recreatePagination();
        return userRights.isModerator() ? "moderatorListReservations": "clientListReservations" ;
    }

    public String prepareView() {
        current = (ReservationDTO) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return userRights.isModerator() ? "moderatorViewReservations" : "clientViewReservations";
    }
    
    public String prepareCreate() {
        current = new ReservationDTO();
        selectedItemIndex = -1;
        return "clientAddReservations";
    }

    public String create() {
        try {
            if(current.getUser() == null) // wylaczony klient czyli praca w trybie wczytania aktualnego klienta
            {
                current.setUser(userEndpoint.getUserByLogin(FacesContext.getCurrentInstance().getExternalContext().getRemoteUser()));//FacesContext.getCurrentInstance().getExternalContext().getRemoteUser()
            }
            //wyliczenie ceny
            Calendar cal = Calendar.getInstance();
            long beginTime;
            long endTime;
            cal.setTime(current.getReservationBegin());
            beginTime = cal.getTimeInMillis();
            cal.setTime(current.getReservationEnd());
            endTime = cal.getTimeInMillis();
            int days =  (int) ((endTime - beginTime) / (24 * 60 * 60 * 1000));
            days = days <= 0 ? 1 : days;
            current.setPrice((double)days * current.getRoom().getPrice());
            
            reservationEndpoint.addNewReservation(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ReservationCreated"));
            return prepareList();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (ReservationDTO) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "clientEditReservations";
    }

    public String update() {
        try {
            //wyliczenie ceny
            Calendar cal = Calendar.getInstance();
            long beginTime;
            long endTime;
            cal.setTime(current.getReservationBegin());
            beginTime = cal.getTimeInMillis();
            cal.setTime(current.getReservationEnd());
            endTime = cal.getTimeInMillis();
            int days =  (int) ((endTime - beginTime) / (24 * 60 * 60 * 1000));
            days = days <= 0 ? 1 : days;
            current.setPrice((double)days * current.getRoom().getPrice());
            
            reservationEndpoint.updateReservationInfo(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ReservationUpdated"));
            return "clientListReservations";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (ReservationDTO) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreatePagination();
        recreateModel();
        return userRights.isModerator() ? "moderatorListReservations" : "clientListReservations";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return userRights.isModerator() ? "moderatorViewReservations" : "clientViewReservations";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return userRights.isModerator() ? "moderatorListReservations" : "clientListReservations";
        }
    }

    private void performDestroy() {
        try {
            reservationEndpoint.deleteReservation(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ReservationDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = reservationEndpoint.getReservationsCount();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = reservationEndpoint.getReservations(selectedItemIndex, selectedItemIndex + 1).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return userRights.isModerator() ? "moderatorListReservations" : "clientListReservations";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return userRights.isModerator() ? "moderatorListReservations" : "clientListReservations";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(reservationEndpoint.getAllReservations(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(reservationEndpoint.getAllReservations(), true);
    }

    @FacesConverter(forClass = ReservationDTO.class)
    public static class ReservationControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            ReservationController controller = (ReservationController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "reservationController");
            return controller.reservationEndpoint.getReservation(getKey(value));
        }

        java.lang.Long getKey(String value) {
            java.lang.Long key;
            key = Long.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Long value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof ReservationDTO) {
                ReservationDTO o = (ReservationDTO) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + ReservationDTO.class.getName());
            }
        }
    }
}
